﻿using System;
using IterationLife.Datas;
using IterationLife.FootballTeaching.Models;
using IterationLife.FootballTeaching.Queries;
using IterationLife.FootballTeaching.Repositories;
using IterationLife.PlatformBackEnd.AppServices.Contracts.FootballTeachings;
using IterationLife.PlatformBackEnd.AppServices.Dtos.FootballTeachings;
using Util.Applications;
using Util.Datas.Queries;
using Util.Exceptions;

namespace IterationLife.PlatformBackEnd.AppServices.Impl.FootballTeachings
{
    /// <summary>
    /// 章节服务
    /// </summary>
    public class ChapterService : ApplicationServiceBase<Chapter, ChapterDto, ChapterQuery>, IChapterService
    {
        /// <summary>
        /// 初始化章节服务
        /// </summary>
        /// <param name="unitOfWork">工作单元</param>
        /// <param name="chapterRepository">章节仓储</param>
        public ChapterService(IApplicationUnitOfWork unitOfWork, IChapterRepository chapterRepository)
            : base(unitOfWork, chapterRepository)
        {
            ChapterRepository = chapterRepository;
        }

        /// <summary>
        /// 章节仓储
        /// </summary>
        protected IChapterRepository ChapterRepository { get; set; }

        /// <summary>
        /// 转换为数据传输对象
        /// </summary>
        /// <param name="entity">实体</param>
        protected override ChapterDto ToDto(Chapter entity)
        {
            return entity.ToDto();
        }

        /// <summary>
        /// 转换为实体
        /// </summary>
        /// <param name="dto">数据传输对象</param>
        protected override Chapter ToEntity(ChapterDto dto)
        {
            return dto.ToEntity();
        }

        /// <summary>
        /// 创建查询对象
        /// </summary>
        /// <param name="param">章节查询实体</param>
        protected override IQueryBase<Chapter> CreateQuery(ChapterQuery param)
        {
            return new Query<Chapter>(param)
                .Filter(t => t.CourseId == param.CourseId)
                .Filter(t => t.Name.Contains(param.Name));
        }

        /// <summary>
        /// 新传输对象
        /// </summary>
        /// <param name="courseId">课程编号</param>
        public ChapterDto NewDto(Guid courseId)
        {
            return new ChapterDto
            {
                CourseId = courseId,
                SortId = ChapterRepository.GetSortId(courseId)
            };
        }

        /// <summary>保存前操作</summary>
        /// <param name="dto">数据传输对象</param>
        protected override void SaveBefore(ChapterDto dto)
        {
            if (dto.SortId == null || dto.SortId < 1)
                throw new Warning("章节数必须大于0");
            base.SaveBefore(dto);
        }
    }
}